package com.itheima.web.controller.company;


import com.github.pagehelper.PageInfo;
import com.itheima.domain.company.Company;
import com.itheima.service.company.CompanyService;
import com.itheima.web.controller.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping(value = "/company")
public class CompanyController extends BaseController {

    @Autowired
    private CompanyService companyService;

    //查询所有企业列表
    @RequestMapping(value = "/list", name = "企业列表")
    public String list(@RequestParam(defaultValue = "1") String pageNum,
                       @RequestParam(defaultValue = "5") String pageSize) {
        PageInfo<Company> pageInfo = companyService.findAll(Integer.valueOf(pageNum), Integer.valueOf(pageSize));
        System.out.println(pageInfo);
        request.setAttribute("pageInfo", pageInfo);
        return "company/company-list";
    }

    //跳转到添加页面，因为WEB-INF下的页面浏览器无法直接访问
    @RequestMapping("/toAdd")
    public String toAdd() {
        return "company/company-add";
    }

    //保存新建企业信息或修改企业信息
    @RequestMapping("/edit")
    public String edit(Company company) {
        if (StringUtils.isEmpty(company.getId())) {
            companyService.save(company);
        } else {
            companyService.update(company);
        }
        return "redirect:/company/list";
    }

    //修改企业信息
    @RequestMapping("/toUpdate")
    public String toUpdate(HttpServletRequest request, String id) {
        Company company = companyService.findById(id);
        request.setAttribute("company", company);
        return "company/company-update";
    }


    //根据ID删除企业记录
    @RequestMapping("/delete")
    public String delete(String id) {
        companyService.deleteCompany(id);
        return "redirect:/company/list";
    }


}
